import h, { renderDom, useEffect } from "./closurejs";

const TodoItem = ({ data, onFinish, onDelete }) => {
  return () => (
    <div>
      {data.type} {data.finish ? "已完成" : "未完成"}
      <button
        style={{
          marginLeft: "10px"
        }}
        onClick={() => {
          onFinish();
        }}
      >
        完成
      </button>
      <button
        style={{
          marginLeft: "10px"
        }}
        onClick={() => {
          onDelete();
        }}
      >
        删除
      </button>
    </div>
  );
};

const app = (_, update) => {
  let arr = [];
  let text;
  let ml = 0; // 定义的变量需要写在这里

  useEffect(
    () => {
      for (let i = 0; i < 10; i++) {
        setTimeout(() => {
          arr.push({
            finish: false,
            type: "测试" + i++
          });
          update();
        }, (i + 1) * 1000);
      }
    },
    () => [] // effect的依赖也需要是函数来返回
  );

  // 需要return一个函数 用于创建闭包 jsx需要放在函数里面
  return () => (
    <div>
      <div>
        <input
          onChange={(e) => {
            text = e.target.value;
          }}
        />
        <button
          onClick={() => {
            arr.push({ type: text, finish: false });
            update();
          }}
        >
          提交
        </button>
      </div>
      <div>
        <p>总数：{arr.length}</p>
        <p>已完成：{arr.filter((item) => item.finish).length} </p>
      </div>
      {arr.map((item) => {
        return (
          <TodoItem
            key={item.type}
            data={item}
            onFinish={() => {
              item.finish = true;
              update();
            }}
            onDelete={() => {
              arr = arr.filter((a) => a.type !== item.type);
              update();
            }}
          />
        );
      })}
      <div style={{ marginLeft: ml + "px", width: "10px", height: "10px" }}>
        111111
      </div>
    </div>
  );
};

renderDom(app, "#app");
